|
|
|
|
|
|
|
This method works for simple objects, but it is limited. You can make much more powerful representations using classes rather than user-defined data types. You can add methods to object classes that allow an object to read itself from a file, write itself into a file, draw itself on a picture box, and perform other tasks that make sense for that kind of object. |
|
|
|
|
|
|
|
|
For example, the following code describes a simple TwoDLine class (TwoD stands for two-dimensional). The class defines public variables to hold the line segment's end points. The Draw method makes the object draw itself on a form, printer, or picture box. |
|
|
|
 |
|
|
|
|
Option Explicit
' A two-dimensional line.
Public X1 As Single
Public Y1 As Single
Public X2 As Single
Public Y2 As Single
' Draw the line on a Form, Printer, or PictureBox. Public Sub Draw(Canvas As Object)
Canvas.Line (X1, Y1)-(X2, Y2)
End Sub |
|
|
|
|
|
|
|
|
You can define other classes to represent other graphical objects such as arcs, circles, ellipses, and rectangles. |
|
|
|
|
|
|
|
|
All these objects have some things in common. They must all be able to draw themselves. Many programs need to know how big an object is. To make this easier, these objects can provide a Bound method that returns the object's minimum and maximum X and Y coordinate values. |
|
|
|
|
|
|
|
|
It would also be convenient if the objects could read and create standard text representations of themselves. This kind of representation is called a serialization. Using serializations, a program can save and restore representations of its objects in a text file or database. |
|
|
|
|
|
|
|
|
To ensure that the objects handle these common tasks consistently, you can make a TwoDObject class that defines these common methods. The other classes can then use the Implements keyword to indicate that they provide the features defined by the TwoDObject class. |
|
|
|
|
|
|
|
|
This not only guarantees that the objects provide these methods in the same way, it also gives a slight performance advantage. A program can refer to any of these objects using the generic TwoDObject data type. It can invoke the methods defined by TwoDObject without knowing the particular type of object it is using. You can achieve the same effect using the Object data type, but using the more specific TwoDObject type is faster. |
|
|
|
|
|
|
|
|
The following code shows how the TwoDObject class defines the common methods provided by the specific object classes. |
|
|
|
|
|